const Router = require('koa-router');
const I18nController = require('../controllers/i18nController');
const multer = require('koa-multer');
const requireAuth = require('../middleware/auth');

const router = new Router();
const i18nController = new I18nController();
// 为导入支持 multipart/form-data 文件上传（内存存储，不落盘）
const upload = multer({ storage: multer.memoryStorage() });

// 列表（支持分页与条件）
router.get('/list', async (ctx) => i18nController.getI18nList(ctx));

// 创建、更新、删除
router.post('/create', requireAuth, async (ctx) => i18nController.createI18nData(ctx));
router.post('/update', requireAuth, async (ctx) => i18nController.updateI18nData(ctx));
router.delete('/delete/:code', requireAuth, async (ctx) => i18nController.deleteI18nData(ctx));

// 导入/导出（放在动态路由之前，避免被/:languageTag匹配到）
router.post(
  '/import',
  requireAuth,
  async (ctx, next) => {
    const ct = (ctx.request.headers && ctx.request.headers['content-type']) || '';
    if (!String(ct).toLowerCase().includes('multipart/form-data')) {
      ctx.status = 400; // 显式设置 HTTP 状态码
      ctx.body = { code: 400, message: '仅支持 multipart/form-data 上传文件', data: null };
      return; // 不继续到后续中间件
    }
    await next();
  },
  upload.single('file'),
  async (ctx) => i18nController.importI18nData(ctx)
);
router.get('/export', async (ctx) => i18nController.exportI18nData(ctx));

// 按语言获取
router.get('/:languageTag', async (ctx) => i18nController.getI18nDataByLanguageTag(ctx));

module.exports = router;